/*
点击单元格

*/

const win = [
    [0,1,2],[3,4,5],[6,7,8],
    [0,3,6],[1,4,7],[2,5,8],
    [0,4,8],[2,4,6]
]
enum Player{
    X = 'x',
    O = 'o'
}

let currentPlayer:string
let steps :number;

let board = document.querySelector('#board') as HTMLDivElement
let cells = document.querySelectorAll('.cell')
let message = document.querySelector('#message') as HTMLDivElement
let winner = document.querySelector('#winner') as HTMLParagraphElement
let restart = document.querySelector('#restart') as HTMLButtonElement

restartGame()

cells.forEach((value,index)=>{
    let cell = value as HTMLDivElement
    cell.addEventListener('click',clickCell,{once: true})
})

function clickCell(event: MouseEvent){
    steps++ 
    let cell = event.target as HTMLDivElement
    cell.classList.add(currentPlayer)

    // 判断胜利
    let isWin = checkWin(currentPlayer)

    if(isWin) {
        message.style.display = 'block'
        winner.innerHTML = currentPlayer.toUpperCase() + "赢了!"
        return
    }
    if(steps === 9){
        message.style.display = 'block'
        winner.innerHTML = "平局"
        return 
    }

    // 切换到下一名玩家
    currentPlayer = currentPlayer === Player.X ? Player.O:Player.X
    
    // 提示
    let gameBoard = document.querySelector('#board') as HTMLDivElement
    gameBoard.classList.remove(Player.X,Player.O)
    gameBoard.classList.add(currentPlayer)
}

function checkWin(player: string){
    let isWin= win.some((ele)=>{
        let cell1 = cells[ele[0]]
        let cell2 = cells[ele[1]]
        let cell3 = cells[ele[2]]
        if(hasClass(cell1,player)&&hasClass(cell2,player)&&hasClass(cell3,player)){
            return true
        }
        return false
    })
    return isWin
}

function hasClass(el:Element,name:string,):boolean{
    return el.classList.contains(name)
}

restart.addEventListener('click',restartGame,{once:true})

function restartGame(){
    message.style.display = 'none'
    board.classList.remove(Player.X,Player.O)
    board.classList.add(Player.X)
    cells.forEach(item=>{
        let cell = item as HTMLDivElement
        cell.classList.remove(Player.X,Player.O)
        cell.removeEventListener('click',clickCell)
        cell.addEventListener('click',clickCell,{once:true})
    })
    steps = 0
    currentPlayer = Player.X
    restart.removeEventListener('click',restartGame)
    restart.addEventListener('click',restartGame,{once:true})
}
